<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>事件委托</title>
    <style>
      .grandpa {
        border: 1px solid #eee;
        width: 300px;
        height: 300px;
      }
    </style>
  </head>
  <body>
    <div class="grandpa">
      <p>grandpa 层级</p>
      <div class="parent">
        <p>parent 层级</p>
        <button class="child1">按钮1</button>
        <button class="child2">按钮2</button>
        <button class="child3">按钮3</button>
      </div>
    </div>

    <script>
      var grandpa = document.querySelector('.grandpa');

      grandpa.addEventListener('click', function (event) {
        console.log(event);
        console.log(event.target, Object.prototype.toString.call(event.target));
        console.log(event.target.tagName);
        console.log(event.currentTarget);
      });

      var child3 = document.querySelector('button.child3');
      child3.addEventListener('click', function (event) {
        event.stopPropagation();
        var p = document.createElement('p');
        p.innerHTML = 'p create by child3 button';
        document.body.appendChild(p);
      });

      // 事件委托
      document.body.addEventListener(
        'click',
        function (event) {
          if (event.target.tagName === 'P') {
            console.log(event.target.innerHTML);
          }
        },
        true
      );
    </script>
  </body>
</html>
